/*
 * Project Name demo
 * File Name MsgListener
 * Package Name com.huxiaosu.demo.socketio
 * Create Time 2023/1/29
 * Create by name：liujie
 */
package com.huxiaosu.demo.socketio.configuration;

import com.corundumstudio.socketio.SocketConfig;
import com.huxiaosu.demo.socketio.config.SocketIoConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

import java.util.List;
import java.util.Map;

/**
 * Description
 *
 * @ClassName: MsgListener
 * @author: liujie
 * @date: 2023/1/29 10:11
 */
@Slf4j
@Configuration
public class MsgListenerConfiguration {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private SocketIoConfig socketIoConfig;
    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(){
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisTemplate.getConnectionFactory());
        List<SocketIoConfig.Channel> channel = socketIoConfig.getChannel();
        channel.forEach(item->{
            try{
                Class className = Class.forName(item.getClassName());
                PatternTopic name = new PatternTopic(item.getName());
                container.addMessageListener((MessageListener) className.newInstance(),name);
                log.info("add [{}] listener success {}",item.getName(),item.getClassName());
            }catch (Exception e){
                // ignore exception
                log.error("add [{}] listener error {}",item.getName(), e.getMessage());
            }

        });
        return container;
    }

}